package com.gs.cd.utils.url;

import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class UrlUtils {

    /**
     * create by seven  2020/11/10
     * 对象转换为get参数
     * 未测试
     */
    public static <T> Map<String, Object> params(T t) {
        HashMap<String, Object> map = new HashMap<>();
        if (t == null) {
            return map;
        }
        Class<?> aClass = t.getClass();
        //获取属性名称
        Field[] declaredFields = aClass.getDeclaredFields();
        //执行get方法
        for (Field declaredField : declaredFields) {
            try {
                Method method = aClass.getMethod("get" + StrUtil.upperFirst(declaredField.getName()));
                Object invoke = method.invoke(t);
                map.put(declaredField.getName(), invoke);
            } catch (NoSuchMethodException e) {
//                log.warn(String.format("没有%s的方法", "get" + StrUtil.upperFirst(declaredField.getName())));
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * create by seven  2020/11/10
     * 自动拼接url
     * http:123/1/23/516
     */
    public static String getUrl(String... url) {
        StringBuilder stringBuilder = new StringBuilder();
        Arrays.stream(url).forEach(s -> {
            if (s.startsWith("/")) {
                s = s.substring(1);
            }
            if (s.endsWith("/")) {
                s = s.substring(0, s.length() - 1);
            }
            stringBuilder.append(s).append("/");
        });
        return stringBuilder.toString();
    }

    /**
     * copy from web
     * URI匹配 支持 * 通配
     * create by hippo  2020/3/3
     *
     * @param reg
     * @param input
     * @return
     */
    public static boolean matching(String reg, String input) {
        if ("/*".equals(reg))
            return true;
        //按 * 切割字符串
        String[] reg_split = reg.split("\\*");
        int index = 0, reg_len = reg_split.length;
        //最后一个字符是否是 '*'
        boolean lastCharIsStar = reg.charAt(reg.length() - 1) == '*';
        while (input.length() > 0) {
            //匹配到最后一段
            if (index == reg_len) {
                return lastCharIsStar;
            }
            String r = reg_split[index++];
            int indexOf = input.indexOf(r);
            if (indexOf == -1) {
                return false;
            }
            //前面匹配成功的就可以不用管了,截取掉直接从新地方开始
            input = input.substring(indexOf + r.length());
        }
        return true;
    }

}
